<template>
  <div class="current-widthdraw-info">
    <Title title="基本信息" style="margin: 0 0 8px 0" />
    <el-form :class="{'mobile-el-form': showMobilePage, 'el-form-dividing': !showMobilePage}" :label-width="showMobilePage?'100px':'110px'" :label-position="showMobilePage?'left':'right'" class="widthdraw-form height55">
      <el-row :gutter="8">
        <el-col :span="8" :class="{ 'full-width': showMobilePage }">
          <el-form-item label="结算名称：" prop="settleName" style="margin-bottom: 0px;">
            <div class="flex">
              <ToolTip :content="widthdrawInfo.settleName" class="widthdraw-item"/>
              <div v-if="isEditEvent" class="button-text edit-btn" @click="openEdit(1)">编辑</div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款类型：" prop="requestFundsType" style="margin-bottom: 0px;">
            {{ widthdrawInfo.requestFundsType | requestFundsTypeStatus }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账户类型：" prop="accountType" style="margin-bottom: 0px;">
            {{ widthdrawInfo.accountType | accountTypeStatus }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="款项归属：" prop="paymentBelongName" style="margin-bottom: 0px;">
            {{ widthdrawInfo.paymentBelongName || '--' }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人：" prop="proposerName" style="margin-bottom: 0px;">
            <!-- {{ widthdrawInfo.proposerName || '--' }} -->
            <CheckUserInfo v-if="widthdrawInfo.proposerName" :label="widthdrawInfo.proposerName" :user-id="widthdrawInfo.proposer" />
            <div v-else>--</div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人部门：" prop="proposerDepartmentName" style="margin-bottom: 0px;">
            {{ widthdrawInfo.proposerDepartmentName || '--' }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属公司：" prop="ourTitle" style="margin-bottom: 0px;">
            <ToolTip :content="widthdrawInfo.ourTitle" placement="top" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同签订：" prop="contractSign" style="margin-bottom: 0px;">
            {{ widthdrawInfo.contractSign | contractSignStatus }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分摊费用：" prop="isAllocation" style="margin-bottom: 0px;">
            {{ widthdrawInfo.isAllocation | isAllocationStatus }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="达人结算确认：" prop="contractSign" style="margin-bottom: 0px;">
            {{ widthdrawInfo.confirmType | confirmType }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="标签：" prop="remarkWithInside" style="margin-bottom: 0;">
            <TagSelect v-model="widthdrawInfo.tag" :is-show-edit-btn="hasRouteAuth('medium:supplierAudit:tagEdit') && isCurrentVersion" mode="detail" @handelClickEdit="handelClickEditTag" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注：" prop="remark" style="margin-bottom: 0px;">
            <div class="flex">
              <ToolTip :content="widthdrawInfo.remark" class="widthdraw-item"/>
              <div v-if="isEditEvent" class="button-text edit-btn" @click="openEdit(2)">编辑</div>
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="widthdrawInfo.examineStatus !== 4" :span="8">
          <el-form-item label="对内备注：" prop="remarkWithInside" style="margin-bottom: 0px;">
            <ToolTip :content="widthdrawInfo.remarkWithInside" />
          </el-form-item>
        </el-col>
        <el-col v-if="[2, 3].includes(widthdrawInfo.accountType)" :span="8">
          <el-form-item label="发票：" prop="invoice" style="margin-bottom: 0px;">
            {{ widthdrawInfo.invoice | invoiceStatus }}
          </el-form-item>
        </el-col>
        <el-col v-if="[2, 3].includes(widthdrawInfo.accountType)" :span="8">
          <el-form-item label="预计取得时间：" prop="planTime" style="margin-bottom: 0px;">
            {{ widthdrawInfo.planTime | format('YYYY/MM/DD') }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划支付日期：" style="margin-bottom: 0;">
            <div class="flex-center">
              <ToolTip :content="widthdrawInfo.planPayTime | format('YYYY/MM/DD')" class="widthdraw-item"/>
              <span v-if="isEditDate" class="date-edit-btn" @click="showPlanPaymentDialog('计划支付日期')">编辑</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实际支付日期：" style="margin-bottom: 0;">
            <div class="flex-center">
              <ToolTip :content="widthdrawInfo.actualPayTime | format('YYYY/MM/DD')" class="widthdraw-item"/>
              <span v-if="isEditDate" class="date-edit-btn" @click="showPlanPaymentDialog('实际支付日期')">编辑</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件：" prop="taxCost" style="margin-bottom: 0px;">
            <div class="ellipsis">
              <FileShowList :file-list="widthdrawInfo.attachment" style="max-width:100%;" is-show-single-file />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="temporaryAttachment" label="临时附件：" style="margin-bottom: 0;">
            <upAttachment
              v-if="canEditTempFile"
              :hide-confirm="true"
              :file-list="widthdrawInfo.temporaryAttachment"
              btn-text="上传附件"
              @complateSetData="complateSetData($event)"
              @removeFileList="removeFileList($event)"
            />
            <FileShowList
              v-else
              ref="fileShowListRef"
              :file-list="widthdrawInfo.temporaryAttachment"
              :show-delete="false"
              style="flex-shrink: 0;"
              is-show-single-file
              icon-show/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <PlanPaymentDialog
      ref="paymentDialogRef"
      :title="paymentDialogTitle"
      :curr-date="paymentDate"
      @confirm="editPlanPaymentDate"
    />
    <!-- 发票列表，无需发票不展示 -->
    <div v-if="[2, 3].includes(widthdrawInfo.accountType) && widthdrawInfo.invoice !== 2" style="margin-top:20px;margin-bottom:32px;">
      <invoiceList
        ref="invoiceListRef"
        v-model="invoiceList"
        :is-creator="isCreator"
        :invoice-event="operationSetEvents.includes(4)"
        :current-widthdraw="currentWidthdraw"
        :is-current-version="isCurrentVersion"
        page-from="detail"
        @attachmentAdd="attachmentAdd"
        @onRowDel="delInvoiceRow" />
    </div>
    <!-- 关联合同 -->
    <relatedContractTable
      v-if="widthdrawInfo.contractSign === 0"
      :list="widthdrawInfo.contractList"
      show-opp-company
      table-title="合同信息"
      style="margin-top: 24px; margin-bottom: 20px" />
    <!-- 收款人列表 -->
    <collectAccount
      v-if="[2, 3].includes(widthdrawInfo.accountType)"
      v-model="widthdrawInfo.collectAccount"
      :account-type="widthdrawInfo.accountType"
      :widthdraw-info="widthdrawInfo"
      :step-one-data="detailData"
      style="margin-bottom: 32px"/>
    <collectMonenyList
      :examin-id="examinId"
      :is-edit-event="isEditEvent"
      :widthdraw-info="widthdrawInfo"
      :request-funds-type="widthdrawInfo.requestFundsType"
      :account-type="widthdrawInfo.accountType"
      :is-not-order="isNotOrder"
      :step-one-data="detailData"
      @getInfo="getInfo" />
    <slot name="middle"/>
    <!-- 分摊费用 -->
    <AllocationAmount v-if="widthdrawInfo.isAllocation" v-model="widthdrawInfo.allocationList" :examin-id="examinId" :is-edit-event="isEditEvent" @getInfo="getInfo" />
    <!-- 编辑结算单名称和备注 -->
    <el-dialog :visible.sync="dialogEditVisible" :close-on-click-modal="false" :class="{'mobile-page-dialog':showMobilePage}" class="small-common-dialog-size" @close="closeDialog">
      <Title :title="editType===1?'编辑结算单名称':'编辑备注'" />
      <div class="edit-main">
        <el-input v-if="editType===1" v-model="editSettleName" :maxlength="30" size="small" placeholder="请输入结算单名称" type="text" />
        <el-input v-if="editType===2" v-model="editRemark" :maxlength="500" size="small" placeholder="请输入备注" type="text" />
      </div>
      <div class="edit-dialog-btn">
        <el-button type="primary" size="small" @click="edit()">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
    <EditTagModule ref="editTagModuleRef" :show-mobile-page="showMobilePage" :edit-tag-api="editTag" :extend-params="{id: currentWidthdraw && currentWidthdraw.id}" :module-type="TAG_MODULES.PROCESS" @callback="editTagCallback" />
  </div>
</template>
<script>
import Title from '@/components/Title';
import FileShowList from '@/components/CreateOrder/fileShowList';
import { accountTypeStatus, payRelationStatus, executePayStatus, contractSignStatus, invoiceStatus, confirmType } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { format } from '@/filters/date';
import { currentWidthdrawInfo, editCurrentWithdraw, editTag, deleteFile, addFile } from '@/api/supplier';
import { planPaymentDateEdit } from '@/api/common';
import { encryption } from '@/utils';
import upAttachment from '@/components/Common/upAttachment/index';
import collectMonenyList from '@/components/SupplierComponent/colletMoneyList/colletMoneyList';
import collectAccount from '@/components/SupplierComponent/colletMoneyList/collectAccount';
import invoiceList from '@/components/SupplierComponent/invoiceList/invoiceList';
import AllocationAmount from '@/components/SupplierComponent/AllocationAmount/index';
import TagSelect from '@/components/Common/tagSelect';
import EditTagModule from '@/components/SupplierComponent/currentWidthdrawInfo/editTag';
import { mapState } from 'vuex';
import { TAG_MODULES } from '@/utils/const';
import { hasRouteAuth } from '@/utils/permission';
import relatedContractTable from '@/components/SupplierComponent/relatedContractTable/relatedContractTable';
import PlanPaymentDialog from '@/components/Common/planPaymentDialog';
import { FIXED_PROCESS_TYPE, EVENT_TYPE } from '@/utils/const/process';

export default {
  components: { Title, FileShowList, upAttachment, collectMonenyList, collectAccount, invoiceList, AllocationAmount, TagSelect, EditTagModule, relatedContractTable, PlanPaymentDialog },
  filters: { accountTypeStatus, payRelationStatus, executePayStatus, moneyFilter, format, invoiceStatus, contractSignStatus, confirmType,
    requestFundsTypeStatus(type) {
      const obj = { 0: '账号付款', 1: '其他付款' };
      return obj[type] || '--';
    },
    isAllocationStatus(type) {
      if (type === false || type || type === 0) {
        return type ? '是' : '否';
      }
      return '--';
    }
  },
  props: {
    currentWidthdraw: { // 当前选中的审批记录
      type: Object,
      default: () => {
        return {
          id: 0,
          examineStatus: 2
        };
      }
    },
    settleId: {
      type: String | Number,
      default: null
    },
    examinId: {
      type: String | Number,
      default: null
    },
    isCreator: { // 是否为发起人
      type: Boolean,
      default: false
    },
    // 当前流程节点，所开启的事件数组
    operationSetEvents: {
      type: Array,
      default: () => []
    },
    processData: {
      type: Object,
      default: () => { return {}; }
    },
    detailData: {
      type: Object,
      default: () => { return {}; }
    },
    isNotOrder: { // 是否为非订单成本付款结算
      type: Boolean,
      default: false
    },
    isCurrentVersion: {// 是否当前版本
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      TAG_MODULES,
      widthdrawInfo: {
        aduitInfo: {
          process: []
        },
        contractList: []
      },
      invoiceList: null,
      editType: 1,
      dialogEditVisible: false,
      editSettleName: '',
      editRemark: '',
      paymentDialogTitle: '',
      paymentDate: null,
      delInvoiceList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isEditEvent() {
      // 编辑说明事件
      // 当开启该事件时，可编辑结算单名称、备注、收款列表说明
      // examineStatus 审批状态进度 0: '待审批', 1: '审批中',2: '未过审',4: '已完成',3: '已作废',5: '已撤回'
      return this.operationSetEvents.includes(10) && this.currentWidthdraw.examineStatus === 1 && this.isExamine && this.isCurrentVersion;
    },
    isEditDate() {
      return this.operationSetEvents.includes(EVENT_TYPE.OPEN_PAY_TIME) && this.currentWidthdraw.examineStatus === 1 && this.isExamine && this.isCurrentVersion;
    },
    isExamine() { // 当前用户是否是当前节点审批人
      const processList = this.processData.list;
      if (!processList || processList.length === 0) return false;
      let item = null;
      processList.forEach(i => {
        // nodeStatus 节点状态： 0：结束 1：进行中 2：未审批
        if (!item && i.nodeStatus === 1) {
          item = i;
        }
      });
      if (!item || item.length === 0) return false;
      let userList = [];
      item.items.forEach(i => {
        userList = userList.concat(i.users);
      });
      return userList.some(i => {
        return i.id === this.userInfo.id;
      });
    },
    canEditTempFile() { // 审批人、创建人可上传删除附件
      let processList = [];
      if (this.widthdrawInfo && this.widthdrawInfo.aduitInfo && this.widthdrawInfo.aduitInfo.process) {
        processList = this.widthdrawInfo.aduitInfo.process;
      }
      const allExamineUserList = [];
      processList.map((process) => {
        process.examineRoles.map((item) => {
          item.aduitors.forEach((aduitors) => {
            if (!allExamineUserList.find(i => i.id === aduitors.id)) {
              allExamineUserList.push(aduitors);
            }
          });
        });
      });
      return (allExamineUserList.find(el => el.id === this.userInfo.id) || this.isCreator) && this.isCurrentVersion;
    }
  },
  created() {
    if (this.currentWidthdraw && this.currentWidthdraw.id) {
      this.getInfo(this.currentWidthdraw.id);
    }
  },
  methods: {
    editTag, hasRouteAuth,
    validateInvole() {
      // invoiceListRef
      return this.$refs.invoiceListRef.validate();
    },
    showPlanPaymentDialog(ref) {
      this.paymentDialogTitle = ref;
      this.paymentDate = ref === '计划支付日期' ? this.widthdrawInfo.planPayTime : this.widthdrawInfo.actualPayTime;
      this.$refs['paymentDialogRef'].dialogVisible = true;
    },
    editPlanPaymentDate(val) {
      const params = {};
      params.id = this.currentWidthdraw.id;
      params.moduleType = FIXED_PROCESS_TYPE.PAYMENT_APPLY;
      if (this.paymentDialogTitle === '计划支付日期') {
        params.planPaymentDate = val;
        params.actualPaymentDate = this.widthdrawInfo.actualPayTime;
      } else {
        params.actualPaymentDate = val;
        params.planPaymentDate = this.widthdrawInfo.planPayTime;
      }
      planPaymentDateEdit(params).then(res => {
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.getInfo(this.currentWidthdraw.id);
        }
      });
    },
    // 附件上传
    complateSetData({ data, fileName }) {
      const bodyData = {
        id: this.currentWidthdraw.id,
        attachment: data
      };
      addFile(bodyData).then(res => {
        this.getInfo(this.currentWidthdraw.id);
      }).catch(err => {
        console.log(err);
      });
    },
    removeFileList({ file, index }) {
      deleteFile(this.currentWidthdraw.id, { url: file.url }).then(res => {
        this.getInfo(this.currentWidthdraw.id);
      }).catch(err => {
        console.log(err);
      });
    },
    // 当前付款信息
    getInfo(withDrawId) {
      // withDrawId 审批单id--需修改由下面的审批单提供
      return currentWidthdrawInfo(withDrawId).then(res => {
        this.handleDetailData(res);
        this.$emit('setIsSaveCollectMoneyData', res.data.isSaveCollectMoneyData);
      }).catch(err => {
        console.error(err);
      });
    },
    handleDetailData(res) { // 处理详情数据
      if (!res.data.collectAccount) {
        res.data.collectAccount = {
          bank: '', payName: '', payNum: '', province: '', subBank: ''
        };
      } else {
        if (res.data.collectAccount.province) {
          res.data.collectAccount.province = res.data.collectAccount.province.replace(/-/g, ',');
        }
      }
      if (res.data.collectMoneyData && res.data.collectMoneyData.list) {
        res.data.collectMoneyData.list.map(item => {
          item.settlementAmount = item.settlementAmount || item.settlementAmount === 0 ? (item.settlementAmount / 100).toFixed(2) : item.settlementAmount;
          item.withdrawAmount = item.withdrawAmount || item.withdrawAmount === 0 ? (item.withdrawAmount / 100).toFixed(2) : item.withdrawAmount;
          item.actualAmount = item.actualAmount || item.actualAmount === 0 ? (item.actualAmount / 100).toFixed(2) : item.actualAmount;
          return item;
        });
      }
      if (res.data.contractList === null) {
        res.data.contractList = [];
      }
      if (res.data.contractSign === 0 && res.data.contractList && res.data.contractList.length) {
        res.data.contractList.map(it => {
          it.userName = it.proposerName;
          if (it.contractSourceType === 1) it.disable = true;
          return it;
        });
      }
      this.invoiceList = res.data.invoiceList || [];// 3.3.4 发票数据改成从详情接口获取
      if (this.$route.query.isDeleteInvoiceId) {
        this.invoiceList.forEach(item => {
          delete item.id;
        });
      }
      res.data.settlementAmountTotal = Math.round(res.data.settlementAmountTotal * 100) / 100;
      this.widthdrawInfo = JSON.parse(JSON.stringify(res.data));
      this.$emit('setCurrentAccountType', res.data.accountType, res.data);
    },
    toContract(item) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(item.id) },
        query: {
          processId: encryption(item.processId)
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    toStr(arr) {
      if (!arr || !arr.length) return '';
      return arr.map(tag => {
        return tag.contractCode || tag.contractName;
      }).join('，');
    },
    /**
     * 编辑结算单名称和备注
     */
    openEdit(editType) {
      // editType 1:编辑结算单名称 2:编辑备注
      this.editRemark = this.widthdrawInfo.remark;
      this.editSettleName = this.widthdrawInfo.settleName;
      this.editType = editType;
      this.dialogEditVisible = true;
    },
    closeDialog() {
      this.dialogEditVisible = false;
      this.editType = 1;
      this.editRemark = '';
      this.editSettleName = '';
    },
    edit() {
      if (!this.editSettleName) {
        this.$message.error('请输入结算单名称');
        return;
      }
      const params = {
        id: this.currentWidthdraw.id,
        settleName: this.editSettleName,
        remark: this.editRemark
      };
      editCurrentWithdraw(params).then(res => {
        if (res.code === 200) {
          this.getInfo(params.id);
          this.$message.success('编辑成功');
          this.closeDialog();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 编辑标签
    handelClickEditTag(tags) {
      this.$refs.editTagModuleRef.openDialog(tags);
    },
    editTagCallback() {
      this.getInfo(this.currentWidthdraw.id);
      this.$message.success('编辑成功');
    },
    delInvoiceRow(val) {
      if (val.id) {
        val.isDelete = 1;
        this.delInvoiceList.push(val);
      }
    },
    // 上传识别的发票需要添加到附件
    attachmentAdd(file) {
      if (Array.isArray(this.widthdrawInfo.temporaryAttachment)) {
        this.widthdrawInfo.temporaryAttachment.push(file);
      } else {
        this.$set(this.widthdrawInfo, 'temporaryAttachment', [file]);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.current-widthdraw-info {
  .full-width {
    width: calc(100% - 28px) !important;
  }
  .widthdraw-form {
    & ::v-deep {
      .el-form-item {
          .el-form-item__label {
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #999999 !important;
            opacity: 1;
            line-height: 30px;
          }
        }
        .el-form-item__content {
          font-size: 14px;
          font-family: PingFang SC;
          line-height: 30px;
          font-weight: 400;
          color: #333333;
          opacity: 1;
        }
    }
  }
  .widthdraw-item {
    max-width: calc(100% - 36px) !important;
  }
}
.widthdraw-contractList {
  display: flex;
  flex-wrap: wrap;
  .widthdraw-contractList-item {
    color: #406eff;
    font-size: 14px;
    cursor: pointer;
  }
}
.flex {
  display: flex;
  align-items: center;
}
.date-edit-btn {
  color: #406EFF;
  margin-left: 4px;
  cursor: pointer;
}
.edit-btn {
  margin-left: 4px;
  margin-right: 4px;
  flex-shrink: 0;
}
.edit-main {
  margin: 16px 0;
}
.edit-dialog-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}
.mobile-page-dialog {
  &::v-deep {
    .el-dialog {
      width: 76% !important;
    }
  }
}
</style>
